import {
    fetchOrders as apiFetchOrders,
    deleteOrder as apiDeleteOrder,
    exportOrders as apiExportOrders,
    fetchDashboardStats as apiFetchDashboardStats,
} from '../services/api'; // 引入 API

const order = {
    namespaced: true, // 启用命名空间
    state() {
        return {
            orders: [], // 存储订单数据
        };
    },
    mutations: {
        SET_ORDERS(state, orders) {
            state.orders = orders;
        },
    },
    actions: {
        fetchOrders({ commit }) {
            return apiFetchOrders().then(response => {
                commit('SET_ORDERS', response.data);
                // 这里可以添加提示信息
            }).catch(() => {
                // 处理错误提示
            });
        },
        deleteOrder({ dispatch }, orderId) {
            return apiDeleteOrder(orderId).then(() => {
                return dispatch('fetchOrders'); // 刷新订单列表
            }).catch(() => {
                // 处理错误提示
            });
        },
        exportOrders() {
            return apiExportOrders().then(response => {
                // 处理导出逻辑，例如下载文件
                const url = window.URL.createObjectURL(new Blob([response.data]));
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', `orders_${Date.now()}.xlsx`);
                document.body.appendChild(link);
                link.click();
                // 这里可以添加提示信息
            }).catch(() => {
                // 处理错误提示
            });
        },
        fetchDashboardStats() {
            return apiFetchDashboardStats().then(response => {
                return response.data; // 返回数据以供组件使用
            });
        },
    },
    getters: {
        orderOrders(state) {
            return state.orders;
        },
    },
};

export default order;
